//
//  XGSettingTableViewController.m
//  HuanXin
//
//  Created by monkey on 2019/7/9.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <MJExtension/MJExtension.h>
#import <Hyphenate/Hyphenate.h>
#import <SVProgressHUD/SVProgressHUD.h>

#import "XGSettingTableViewController.h"

#import "XGSettingGroupModel.h"
#import "XGSettingItemModel.h"

#import "NSFileManager+Extension.h"
#import "MBProgressHUD+Extension.h"

@interface XGSettingTableViewController () <UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;
    /// 数据模型
    NSArray<XGSettingGroupModel *> *_groupsArr;
}

@end

@implementation XGSettingTableViewController

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    [super loadView];
    
    [self setUpUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"设置";
    [self setUpTableView];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self calculateCacheSize];
    });
    DEBUG_Log(@"%@",NSHomeDirectory());
}

- (void)dealloc
{
    DEBUG_Log_Method;
}

#pragma mark - UITableViewDataSource && UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.groupsArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _groupsArr[section].items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *const reuseIdentifier = @"reuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
    }
    
    XGSettingItemModel *itemModel = _groupsArr[indexPath.section].items[indexPath.row];
    cell.textLabel.text = itemModel.title;
    cell.detailTextLabel.text = itemModel.detailText;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XGSettingItemModel *itemModel = _groupsArr[indexPath.section].items[indexPath.row];
    if (itemModel.funcName != nil) {
        SEL selector = NSSelectorFromString(itemModel.funcName);
        IMP imp = [self methodForSelector:selector];
        void (*fun)(id,SEL) = (void *)imp;
        fun(self,selector);
    }
}

#pragma mark - 其他方法

- (void)setUpUI
{
    [self.view addSubview:[self tableView]];
    _tableView.frame = self.view.bounds;
}

- (void)setUpTableView
{
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    _tableView.sectionHeaderHeight = 10;
    _tableView.sectionFooterHeight = 0;
    
    _tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
}

// 计算缓存大小
- (void)calculateCacheSize
{
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    [NSFileManager getFileSize:cachePath completion:^(NSUInteger fileSize) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        dispatch_async(dispatch_get_main_queue(), ^{
            UITableViewCell *cell = [self->_tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f MB",fileSize / 1000.f / 1000.f];
        });
    }];
}

// 清理缓存
- (void)clearCache
{
    [self alertWithTitle:@"确定要清理所有缓存吗?" message:nil destructiveTitle:@"确定" destructiveAction:^(UIAlertAction * _Nullable action) {
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        [NSFileManager removeFilePath:cachePath completion:^(NSError * _Nullable error) {
            if (error != nil) {
                return;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"清除成功!"];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                UITableViewCell *cell = [self->_tableView cellForRowAtIndexPath:indexPath];
                cell.detailTextLabel.text = @"0.00 MB";
            });
        }];
    } defaultTitle:@"取消" defaultAction:nil];
}

// 退出登录
- (void)logOut
{
    [self alertWithTitle:@"确定要退出登录吗?" message:nil destructiveTitle:@"确定" destructiveAction:^(UIAlertAction * _Nullable action) {
        [MBProgressHUD showMessage:@"正在退出..." toView:self.view];
        [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                // 切换根控制器
                [[NSNotificationCenter defaultCenter] postNotificationName:XGSwitchApplicationRootViewControllerNotification object:nil userInfo:@{XGRootViewControllerClassNameKey: @"XGLoginViewController"}];
            });
        }];
    } defaultTitle:@"取消" defaultAction:nil];
}

#pragma mark - 懒加载

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    }
    
    return _tableView;
}

- (NSArray<XGSettingGroupModel *> *)groupsArr
{
    if (_groupsArr == nil) {
        _groupsArr = [XGSettingGroupModel mj_objectArrayWithFilename:@"items.plist"];
    }
    
    return _groupsArr;
}

@end
